Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

Solution:

  1. public class Solution {
  2. public int rangeBitwiseAnd(int m, int n) {
  3. return rangeBitwiseAnd(m, n, 0x80000000);
  4. }
  5. int rangeBitwiseAnd(int m, int n, int shift) {
  6. // edge case
  7. if (m == 0) return 0;
  8. // find highest bit of m
  9. while ((shift & m) == 0) {
  10. if ((shift & n) != 0) return 0;
  11. shift >>>= 1;
  12. }
  13. return shift + rangeBitwiseAnd(m - shift, n - shift, shift);
  14. }
  15. }